package com.msgChannel;

import com.utils.CacheConstants;
import com.utils.HttpUtils;
import com.utils.MD5Crypter;
import com.utils.Returnsms;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
@ConfigurationProperties(prefix = "msg")
public class SendMsgCilent {

    private Logger logger = LoggerFactory.getLogger(SendMsgCilent.class);


    private String host;


    private String userid;


    private String account;


    private String password;


    private String mm;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static Map<String, String> params = new HashMap<>();

    @PostConstruct
    public void init() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = sf.format(System.currentTimeMillis());
        String originalString = this.account + this.password + timestamp;
        String sign = MD5Crypter.md5Encrypt(originalString);
        params.put("userid", this.userid);
        params.put("account", this.account);
        params.put("password", this.password);
        params.put("timestamp", timestamp);
        params.put("sign", sign);
        params.put("sendTime", "");
        params.put("action", "send");
        params.put("extno", "");
    }


    /**
     * 短信发送，
     *
     * @param mobile  接收短信号码为","（英文逗号）间隔开
     * @param content
     * @param
     * @return
     */
    public boolean sendMsg(String mobile, String content) {
        String result = "";
//        StringBuffer buffer = new StringBuffer();
//        buffer.append(content);
        params.put("content", content);
//        try {
//            params.put("content", new String(buffer.toString()
//                    .getBytes("UTF-8")));
//        } catch (UnsupportedEncodingException e1) {
//            e1.printStackTrace();
//        }
        params.put("mobile", mobile);
        logger.info("params:{}", params);

        boolean t = false;
        try {
            result = HttpUtils.invokePostForm(this.host, params, 5000);
            Returnsms sb = this.XMLStringToBean(result);
            logger.info("params:{}", params);
            logger.info("Send msg Result:{}", result);
            if (sb.getMessage().equals("ok")) {
                t = true;
            } else {
                logger.info("Send msg fail mobile:{} , Result:{}", mobile, result);
            }
        } catch (Exception e) {
            logger.error("自定义短信发送异常:{}", e);
        }
        return t;
    }

    public boolean validateCode(String mobile, String code) {
        // 发送验证码
        Map<String, String> params = new HashMap<>();
        Boolean t = false;
        params.put("code", code);
        String jgApiKey = "09c372b1920122d55f7127cc";
        String jgMasterSecret = "38d6686004d7921aac4309d1";
        String conten = jgApiKey + ":" + jgMasterSecret;// "09c372b1920122d55f7127cc:38d6686004d7921aac4309d1"
        String base64_auth_string = Base64.getEncoder().encodeToString(
                conten.getBytes());
        try {
            String msg_Id = stringRedisTemplate.opsForValue().get(CacheConstants.SEND_MOBILE.getValue() + mobile);
            logger.info("validateCode msgId:{}", msg_Id);
            if (StringUtils.isNotEmpty(msg_Id)) {
                String url = "https://api.sms.jpush.cn/v1/codes/" + msg_Id + "/valid";
                t = HttpUtils.invokePostaddH(url, params, 5000, base64_auth_string);
                if (t)
                    stringRedisTemplate.delete(CacheConstants.SEND_MOBILE + mobile);
            } else {
                logger.info("该手机号msgId为空，手机号为：{}", mobile);
            }

        } catch (ClientProtocolException e) {
            logger.error("极光验证码连接异常：{}", e);
        } catch (IOException e) {
            logger.error("极光验证码异常：{}", e);
        }
        return t;
    }

    /**
     * 极光短信发送，
     *
     * @param mobile 接收短信为英文,（英文逗号）间隔开
     * @return
     */
    public Boolean sendVerificationCode(String mobile,String tempId) {
        // 发送验证码
        boolean sendResult = false;
        String default_temp_id = "5";

        if(StringUtils.isBlank(tempId))
            tempId = default_temp_id;

        Map<String, String> params = new HashMap<>();
        params.put("temp_id", tempId);
        params.put("mobile", mobile);
        String content = "09c372b1920122d55f7127cc:38d6686004d7921aac4309d1";
        String base64_auth_string = Base64.getEncoder().encodeToString(content.getBytes());
        String urlStr = "https://api.sms.jpush.cn/v1/codes";

        try {
            String result = HttpUtils.invokePostAddAuth(urlStr, params, 5000, base64_auth_string);
            logger.info("极光发送验证码返回的msgId={},mobile={}", result, mobile);// {"msg_id":"4c40ec52-56e3-4868-be80-95d4eb5a4c48"}

            JSONObject resultObject = new JSONObject(result);
            String msgId = resultObject.getString("msg_id");
            logger.info("msgId:{}", msgId);

            stringRedisTemplate.opsForValue().set(CacheConstants.SEND_MOBILE.getValue() + mobile, msgId, 300, TimeUnit.SECONDS);

            sendResult = true;
        } catch (IOException e) {
            logger.info("极光发送验证码短信异常！mobile={}", mobile);
            logger.error("极光发送验证码短信异常", e);
        }
        return sendResult;
    }

    public Returnsms XMLStringToBean(String xmlStr) {
        Returnsms ben = new Returnsms();
        try {
            JAXBContext context = JAXBContext.newInstance(Returnsms.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            ben = (Returnsms) unmarshaller.unmarshal(new StringReader(xmlStr));
        } catch (JAXBException e) {
            logger.error("XML String to bean error: {}", e);
        }
        return ben;
    }


    public void setHost(String host) {
        this.host = host;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setMm(String mm) {
        this.mm = mm;
    }
}
